
import socket
import threading
import time

class UDPServer:
    def __init__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.servAddr = None
        self.servSend = None
        self.servRecv = None
        self.recvCb = None
        self.clientList = []  # 保存客户端IP地址的列表
        self._stop_flag = False  # 标志位，用于控制线程的执行

    def setPort(self, port):
        self.sock.bind(('', port))
        self.servAddr = ('', port)
        self.servSend = ('255.255.255.255', port)
        self.servRecv = ('', port)

    def sendUdpMsg(self, msg):
        for clientAddr in self.clientList:  # 遍历客户端IP地址列表，向每个客户端发送消息
            self.sock.sendto(msg.encode(), clientAddr)

    def set_callback(self, cb):
        self.recvCb = cb
        self.sock.setblocking(False)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.sock.settimeout(10)
        threading.Thread(target=self.recv).start()

    def recv(self):
        while not self._stop_flag:
            try:
                data, addr = self.sock.recvfrom(1024)
                if addr not in self.clientList:  # 如果客户端IP地址不在列表中，则添加到列表中
                    self.clientList.append(addr)
                self.recvCb(data.decode())
            except socket.timeout:
                pass
            except KeyboardInterrupt:
 
                self.stop()   
            time.sleep(0.01)
        
    def stop(self):
        
        self._stop_flag = True
        self.sock.close()
        print("server over")